<template>
    <div>
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" inline>
                <el-form-item label="广告主ID" prop="ad_account_id">
                    <el-select v-model="queryParams.ad_account_id" filterable remote reserve-keyword
                        placeholder="请选择广告主ID" :remote-method="remoteSearchCorporation" :loading="corporationLoading"
                        style="width: 380px !important;" clearable>
                        <el-option v-for="item in corporationOptions" :key="item.ad_account_id"
                            :label="`${item.ad_account_id}（${item.corporation_name}）`" :value="item.ad_account_id">
                            <div class="flex flex-col">
                                <span>{{ item.ad_account_id }}</span>
                                <span class="text-gray-400 text-xs">{{ item.corporation_name }}</span>
                            </div>
                        </el-option>
                        <template #footer>
                            <div class="flex justify-between items-center p-2 border-t">
                                <span class="text-sm text-gray-500">共 {{ corporationTotal }} 项</span>
                                <el-pagination small layout="prev, pager, next" :total="corporationTotal"
                                    :page-size="corporationPageSize" :current-page="corporationCurrentPage"
                                    @current-change="handleCorporationPageChange" />
                            </div>
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item label="广告主名称" prop="corporation_name">
                    <el-input class="w-[280px]" v-model="queryParams.corporation_name" clearable
                        placeholder="请输入广告主名称" />
                </el-form-item>
                <el-form-item label="广告组ID" prop="ad_group_id">
                    <el-input class="w-[280px]" v-model="queryParams.ad_group_id" clearable placeholder="请输入广告组ID" />
                </el-form-item>
                <el-form-item label="广告组名称" prop="ad_group_name">
                    <el-input class="w-[280px]" v-model="queryParams.ad_group_name" clearable placeholder="请输入广告组名称" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none" v-loading="pager.loading" shadow="never">
            <!-- 隐藏的激活按钮 -->
            <div style="position: absolute; top: 10px; right: 10px; z-index: 1000;">

                <el-button type="text" size="small" @click="clickPlacementLogshow()"
                    style="opacity: 0.1; color: transparent;" title="">
                    激活
                </el-button>
            </div>

            <!-- 配置数量 -->
            <div class="config-stats-container">
                <div class="config-stat-item">
                    <div class="config-stat-content">
                        <div class="config-stat-label">授权主体</div>
                        <div class="config-stat-value">
                            <span class="current-count">{{ vdata.zt_num }}</span>
                            <span class="separator">/</span>
                            <span class="total-count">{{ vdata.company_num === 0 ? '无限制' : vdata.company_num }}</span>
                        </div>
                    </div>
                </div>

                <!-- <div class="config-stat-item">
                    <div class="config-stat-content">
                        <div class="config-stat-label">可授权主体数</div>
                        <div class="config-stat-value">
                            <span class="current-count">0</span>
                            <span class="separator">/</span>
                            <span class="total-count">100</span>
                        </div>
                    </div>
                </div> -->

                <div class="config-stat-item">
                    <div class="config-stat-content">
                        <div class="config-stat-label">账户数</div>
                        <div class="config-stat-value">
                            <span class="current-count">{{ vdata.account_num }}</span>
                            <span class="separator">/</span>
                            <span class="total-count">{{ vdata.tencent_advertising_num === 0 ? '无限制' :
                                vdata.tencent_advertising_num }}</span>
                        </div>
                    </div>
                </div>

                <!-- <div class="config-stat-item">
                    <div class="config-stat-content">
                        <div class="config-stat-label">可用账户数</div>
                        <div class="config-stat-value">
                            <span class="current-count">0</span>
                            <span class="separator">/</span>
                            <span class="total-count">100</span>
                        </div>
                    </div>
                </div> -->

                <!-- <div class="config-stat-item">
                    <div class="config-stat-content">
                        <div class="config-stat-label">已投放用户数</div>
                        <div class="config-stat-value">
                            <span class="current-count">0</span>
                            <span class="separator">/</span>
                            <span class="total-count">100</span>
                        </div>
                    </div>
                </div>

                <div class="config-stat-item">
                    <div class="config-stat-content">
                        <div class="config-stat-label">可投放用户数</div>
                        <div class="config-stat-value">
                            <span class="current-count">0</span>
                            <span class="separator">/</span>
                            <span class="total-count">100</span>
                        </div>
                    </div>
                </div> -->
            </div>
            <div class="mt-4">
                <el-table :data="pager.lists" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="广告主账户" show-overflow-tooltip>
                        <template #default="scope">
                            <div>{{ scope.row.corporation_name }}</div>
                            <div class="text-gray-400 text-sm mt-1 flex items-center">
                                <span class="inline-block w-[90px]">ID:</span>
                                <span>{{ scope.row.ad_account_id }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;"
                                    @click="copyToClipboard(scope.row.ad_account_id)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                            <div class="text-gray-400 text-sm mt-1 flex items-center">
                                <span class="inline-block w-[90px]">授权账户ID:</span>
                                <span>{{ scope.row.account_id }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;"
                                    @click="copyToClipboard(scope.row.account_id)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="广告组ID" prop="ad_group_id" show-overflow-tooltip>
                        <template #default="scope">
                            <div class="flex items-center">
                                <span>{{ scope.row.ad_group_id }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;"
                                    @click="copyToClipboard(scope.row.ad_group_id)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="广告组名称" prop="ad_group_name" show-overflow-tooltip>
                        <template #default="scope">
                            <div class="flex items-center">
                                <span>{{ scope.row.ad_group_name }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;"
                                    @click="copyToClipboard(scope.row.ad_group_name)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="霸屏持续投放" prop="24hours_state">
                        <template #default="scope">
                            <el-switch active-text="开启" :active-value="1" active-color="#2fa1fa" inactive-text="关闭"
                                :inactive-value="2" inactive-color="#9c9c9c" v-model="scope.row.hour_push_state"
                                @click="handle24HousePlacement(scope.row)">

                            </el-switch>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="430" fixed="right">
                        <template #default="{ row }">
                            <el-button v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handlePlacement(row)">
                                投放
                            </el-button>

                            <el-button v-if="clickshowPlacementLog"
                                v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handlePlacementLog(row)">
                                投放记录
                            </el-button>

                            <el-button v-if="row.tenantInfo?.link_enable === 0"
                                v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handleCreateWebUrl(row)">
                                投放数量设置
                            </el-button>

                            <el-button v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handleBlacklist(row)">
                                投放黑名单
                            </el-button>

                            <el-button v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handleWechatList(row)">
                                关联微信号
                            </el-button>

                            <el-button v-perms="['ads.tencent_advertising_user_ad_list/placement']" type="primary" link
                                @click="handleCustomer(row)">
                                客群库
                            </el-button>

                            <el-button v-perms="['ads.tencent_advertising_user_ad_list/delete']" type="danger" link
                                @click="handleDelete(row)">
                                删除
                            </el-button>

                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex mt-4 justify-end">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <placement-popup v-if="showPlacement" ref="placementRef" :dict-data="dictData" @success="getLists"
            @close="showPlacement = false" />
        <placement-log-popup v-if="showPlacementLog" ref="placementLogRef" :ad_group_id="showPlacementLogAdGroupId"
            @success="showPlacementLog = false" @close="showPlacementLog = false" />

        <WechatListPopup v-if="showWechatList" ref="wechatListRef" :ad_group_id="wechatListAdGroupId"
            @close="showWechatList = false" />

        <CustomerPopup v-if="showCustomer" ref="customerRef" :id="customerAdGroupId"
            @close="showCustomer = false" />

        <BlacklistPopup v-if="showBlacklist" ref="blacklistRef" :ad_group_id="blacklistAdGroupId"
            @close="showBlacklist = false" />

    </div>
</template>

<script lang="ts" setup name="tencentAdvertisingUserAdListLists">
import {
    apiTencentAdvertisingUserAdList24HourPlacement,
    apiTencentAdvertisingUserAdListDelete,
    apiTencentAdvertisingUserAdListLists,
    apiTencentAdvertisingUserAdListPlacementRefresh,
    apiTencentAdvertisingUserAdListCreateWebUrl,
    getCount
} from '@/api/tencent_advertising_user_ad_list'
import { useDictData } from '@/hooks/useDictOptions'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { timeFormat } from '@/utils/util'

import PlacementPopup from './placement.vue'
import PlacementLogPopup from './placement_log.vue'
import WechatListPopup from './wechat_list.vue'
import BlacklistPopup from './blacklist.vue'
import CustomerPopup from './customer.vue'
import {
    ElLoading,
    ElMessage,
    ElMessageBox,
    type ElMessageBoxOptions,
    ElNotification
} from 'element-plus'
import { CopyDocument } from '@element-plus/icons-vue'  // 导入复制图标
import axios from 'axios'
import useUserStore from '@/stores/modules/user'


const placementRef = shallowRef<InstanceType<typeof PlacementPopup>>()
const placementLogRef = shallowRef<InstanceType<typeof PlacementLogPopup>>()
const wechatListRef = shallowRef<InstanceType<typeof WechatListPopup>>()
const blacklistRef = shallowRef<InstanceType<typeof BlacklistPopup>>()
const customerRef = shallowRef<InstanceType<typeof CustomerPopup>>()
// 是否显示投放框
const showPlacement = ref(false)

// 是否显示投放记录框

const showPlacementLog = ref(false)
const showPlacementLogAdGroupId = ref()

// 新增弹窗相关代码
const showWechatList = ref(false)
const wechatListAdGroupId = ref()
const handleWechatList = async (data: any) => {
    wechatListAdGroupId.value = data.ad_group_id
    showWechatList.value = true
    await nextTick()
    wechatListRef.value?.open('wechat_list')
}

// 新增黑名单弹窗相关代码
const showBlacklist = ref(false)
const blacklistAdGroupId = ref()
const handleBlacklist = async (data: any) => {
    blacklistAdGroupId.value = data.ad_group_id
    showBlacklist.value = true
    await nextTick()
    blacklistRef.value?.open('blacklist')
}

// 新增客群库弹窗相关代码
const showCustomer = ref(false)
const customerAdGroupId = ref()
const handleCustomer = async (data: any) => {
    customerAdGroupId.value = data.id
    showCustomer.value = true
    await nextTick()
    customerRef.value?.open()
}

// 查询条件
const queryParams = reactive({
    tenant_id: '',
    account_id: '',
    ad_account_id: '',
    corporation_name: '',
    ad_group_id: '',
    ad_group_name: '',
    dynamic_creative_id: '',
    dynamic_creative_name: '',
})

//限制数量
const vdata = reactive({
    account_num: 0,
    company_num: 0,
    tencent_advertising_num: 0,
    zt_num: 0,
})


// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id)
}
const clickshowPlacementLog = ref(false)

let count = 0;

// 重置点击次数
const resetClickCount = () => {
    count = 0;
    clickshowPlacementLog.value = false;
    console.log('点击次数已重置')
}

// 
const clickPlacementLogshow = () => {
    console.log('clickPlacementLogshow 被点击')
    count++;
    console.log('当前点击次数:', count)
    if (count >= 10) {
        console.log('检测到 clickshowPlacementLog 变为 true，准备显示投放记录')
        // 这里可以添加显示投放记录的逻辑
        // 例如：显示一个提示或者自动打开投放记录弹窗
        clickshowPlacementLog.value = true
        ElMessage.info('投放记录功能已激活');
    } else {
        console.log(`还需要点击 ${10 - count} 次才能激活投放记录功能`)
    }
}



// 获取字典数据
const { dictData } = useDictData('')

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiTencentAdvertisingUserAdListLists,
    params: queryParams
})


// 投放
const handlePlacement = async (data: any) => {
    showPlacement.value = true
    await nextTick()
    placementRef.value?.open('placement')
    placementRef.value?.setFormData(data)
}

//投放记录
const handlePlacementLog = async (data: any) => {
    showPlacementLogAdGroupId.value = data.ad_group_id
    showPlacementLog.value = true
    await nextTick()
    placementLogRef.value?.open('placement_log')
}

// 投放外链
const handleCreateWebUrl = async (data: any) => {
    const loading = ElLoading.service({
        lock: true,
        text: '生成外链中...'
    })
    try {
        const res = await apiTencentAdvertisingUserAdListCreateWebUrl({
            id: data.id,
            ad_group_id: data.ad_group_id,
            ad_group_name: data.ad_group_name
        })
        console.log('resssss', res)
        if (res.url) {
            const webUrl = res.url
            ElMessage.success('外链生成成功')

            // 显示外链并询问是否复制
            ElMessageBox.confirm(
                `外链生成成功！\n\n外链地址：${webUrl}\n\n是否复制到剪贴板？`,
                '投放外链',
                {
                    confirmButtonText: '复制',
                    cancelButtonText: '关闭',
                    type: 'success',
                    dangerouslyUseHTMLString: false,
                    customClass: 'web-url-dialog'
                }
            ).then(() => {
                // 复制到剪贴板
                navigator.clipboard.writeText(webUrl).then(() => {
                    ElMessage.success('外链已复制到剪贴板')
                }).catch(() => {
                    ElMessage.error('复制失败，请手动复制')
                })
            }).catch(() => {
                // 用户点击取消，不做任何操作
            })
        } else {
            ElMessage.error('外链生成失败')
        }
    } catch (error) {
        console.error('生成外链出错:', error)
        ElMessage.error('外链生成失败')
    } finally {
        loading.close()
    }
}

// 投放刷新
const handlePlacementRefresh = async (data: any) => {
    const loading = ElLoading.service({
        lock: true,
        text: '投放中...'
    })
    let res = await apiTencentAdvertisingUserAdListPlacementRefresh(data)
    console.log(res, 'resresresresresresresresresresresresresres');

    if (res.data.code == 1) {
        ElMessage.success(res.data.msg)
    } else {
        ElMessage.error(res.data.msg)
    }
    loading.close()
}

// 删除
const handleDelete = async (row: any) => {
    await feedback.confirm('确定要删除？')
    await apiTencentAdvertisingUserAdListDelete({ id: row.id, account_id: row.account_id, ad_group_id: row.ad_group_id, ad_account_id: row.ad_account_id })
    getLists()
}

const handle24HousePlacement = async (data: any[]) => {
    const loading = ElLoading.service({
        lock: true,
        text: '投放开启中...'
    })
    let params = { "id": data.id, "hour_push_state": data.hour_push_state }
    let res = await apiTencentAdvertisingUserAdList24HourPlacement(params)
    if (res.data.code == 1) {
        ElMessage.success(res.data.msg)
    } else {
        ElMessage.error(res.data.msg)
    }
    loading.close()
    getLists()
}

// 广告主名称下拉选项
const corporationOptions = ref([])
const corporationLoading = ref(false)
const corporationTotal = ref(0)
const corporationCurrentPage = ref(1)
const corporationPageSize = ref(10)
const corporationKeyword = ref('')

/**
 * 远程搜索广告主名称
 * @param {string} query - 搜索关键词
 */
const remoteSearchCorporation = (query) => {
    corporationKeyword.value = query
    corporationCurrentPage.value = 1
    fetchCorporationOptions()
}
const url = `${import.meta.env.VITE_APP_BASE_URL || ''}`
const userStore = useUserStore()
/**
 * 获取广告主名称选项
 */
const fetchCorporationOptions = async () => {
    corporationLoading.value = true
    try {
        const params = {
            page: corporationCurrentPage.value,
            limit: corporationPageSize.value,
            ad_account_id: corporationKeyword.value,
        }
        const headers = {
            "Token": userStore.token,
        }

        const response = await axios.get(url + '/tenantapi/ads.tencent_advertising_user_ad/lists', { params, headers })

        if (response.data.code === 1) {
            corporationOptions.value = response.data.data.lists || []
            corporationTotal.value = response.data.data.count || 0
        } else {
            ElMessage.error(response.data.msg || '获取广告主列表失败')
            corporationOptions.value = []
            corporationTotal.value = 0
        }
    } catch (error) {
        console.error('获取广告主列表出错:', error)
        ElMessage.error('获取广告主列表失败')
        corporationOptions.value = []
        corporationTotal.value = 0
    } finally {
        corporationLoading.value = false
    }
}

/**
 * 处理广告主名称分页变化
 * @param {number} page - 页码
 */
const handleCorporationPageChange = (page) => {
    corporationCurrentPage.value = page
    fetchCorporationOptions()
}

// 初始加载广告主名称选项
onMounted(() => {
    fetchCorporationOptions()

    // 添加键盘事件监听
    document.addEventListener('keydown', handleKeyDown)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyDown)
})

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
    // 按 Ctrl + Shift + L 触发投放记录激活
    if (event.ctrlKey && event.shiftKey && event.key === 'L') {
        event.preventDefault()
        clickPlacementLogshow()
    }
}

getLists()
// 复制到剪贴板功能
const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text).then(() => {
        ElMessage.success('复制成功')
    }).catch(() => {
        ElMessage.error('复制失败')
    })
}


const getCountData = async () => {
    const res = await getCount()
    vdata.account_num = res.account_num
    vdata.company_num = res.company_num
    vdata.tencent_advertising_num = res.tencent_advertising_num
    vdata.zt_num = res.zt_num
}

getCountData()


</script>

<style scoped>
/* 确保下拉选项宽度与选择器一致 */
:deep(.el-select-dropdown__wrap) {
    min-width: 380px;
}
</style>

<style>
/* 外链弹框样式 */
.web-url-dialog {
    width: 600px !important;
    max-width: 80vw !important;
}

.web-url-dialog .el-message-box__content {
    padding: 20px !important;
    font-size: 14px !important;
    line-height: 1.6 !important;
}

.web-url-dialog .el-message-box__message {
    word-break: break-all !important;
    white-space: pre-wrap !important;
}

.web-url-dialog .el-message-box__btns {
    padding: 15px 20px 20px !important;
}
</style>


<style scoped>
/* 配置统计样式 */
.config-stats-container {
    display: flex;
    gap: 12px;
    margin-left: 16px;
    align-items: center;
}

.config-stat-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 12px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    transition: all 0.3s ease;
    min-width: 140px;
    height: 32px;
}

.config-stat-item:hover {
    background: #f1f5f9;
    border-color: #3b82f6;
}

.config-stat-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: white;
    background: linear-gradient(135deg, #10b981, #34d399);
    box-shadow: 0 3px 10px rgba(16, 185, 129, 0.3);
    flex-shrink: 0;
}

.config-stat-icon.available {
    background: linear-gradient(135deg, #3b82f6, #60a5fa);
    box-shadow: 0 3px 10px rgba(59, 130, 246, 0.3);
}

.config-stat-content {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.config-stat-label {
    font-size: 12px;
    color: #6b7280;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.config-stat-value {
    display: flex;
    align-items: center;
    gap: 2px;
    font-size: 14px;
    font-weight: 600;
    color: #1f2937;
}

.current-count {
    color: #10b981;
}

.separator {
    color: #9ca3af;
    font-weight: 500;
}

.total-count {
    color: #6b7280;
    font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .config-stats-container {
        flex-direction: column;
        gap: 12px;
        margin-left: 0;
        margin-top: 12px;
    }

    .config-stat-item {
        min-width: auto;
        width: 100%;
    }
}
</style>